package com.wing.res.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.service.ProductDetailService;
import com.wing.res.model.request.ResDrawVersionUpdateForm;
import com.wing.res.model.response.ResProductDrawVo;
import com.wing.res.service.ResProductDrawService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.DrawExcelIn;
import com.wing.web.excel.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * sku图纸信息
 * @version 1.1.0
 * @Author hz
 * @Date 2024-10-06 10:46
 **/
@Slf4j
@Validated
@Api(value = "产品图纸信息", tags = "#/res/draw/proDraw")
@RestController("resPlanDrawController")
@RequestMapping("res/admin/proDraw")
public class ResProductDrawController {

    /**
     * 图纸表
     */
    @Resource
    private ResProductDrawService resProductDrawService;

    /**
     *查看图纸 以及他的历史版本
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @param status
     * @param isDefault
     * @param code
     * @param name
     * @param skuCode
     * @param skuNo
     * @return
     */
    @ApiOperation(value = "查看sku图纸列表", notes = "搜索-图纸")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ResProductDrawVo> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String status
            ,String isDefault
            ,String code
            ,String name
            ,String skuCode
            ,String bookCode
            ,String skuNo
            ,String productDetailId
    ) {
        Page<ResProductDrawVo> pg = new Page<>(page, limit);
        Map<String,Object> map = new HashMap();
        map.put("status", status);
        map.put("isDefault", isDefault);
        map.put("code", code);
        map.put("name", name);
        map.put("skuCode", skuCode);
        map.put("taskId", bookCode);
        map.put("skuNo", skuNo);
        map.put("productDetailId", productDetailId);

        Page<ResProductDrawVo> list = resProductDrawService.getListByMap(pg,map);
        list.getRecords().stream().forEach(info->{

            info.setDrawTypeName(MaintenanceEnum.DrawTypeEnum.getNameByCode(info.getDrawType()));
            if (StrUtil.isNotEmpty(info.getTaskCode())){
                info.setTaskNo(info.getTaskCode());
            }else{
                info.setTaskNo(info.getBookCode());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    /**
     * 作废
     * @param id
     * @return
     */
    @ApiOperation(value = "作废图纸", notes = "图纸-作废")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/cancellation/{id}")
    public JsonResult cancellation(@PathVariable("id") String id) {
        int cancellation = resProductDrawService.cancellation(id);
        if (cancellation > 0) {
            return JsonResult.success("操作成功");
        }else if (cancellation == -1){
            return JsonResult.fail("操作失败! 仅可作废非默认图纸");
        }else{
            return JsonResult.fail("操作失败");
        }
    }


    /**
     * 恢复
     * @param id
     * @return
     */
    @ApiOperation(value = "恢复图纸", notes = "图纸-恢复")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/recover/{id}")
    public JsonResult recover(@PathVariable("id") String id) {
        int cancellation = resProductDrawService.recover(id);
        if (cancellation > 0) {
            return JsonResult.success("操作成功");
        }else{
            return JsonResult.fail("操作失败");
        }
    }

    /**
     * 修改客户图纸版本信息
     * @param form
     * @return
     */
    @ApiOperation(value = "图纸-版本变更", notes = "图纸-版本变更")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/updateDrawVersion")
    public JsonResult updateDrawVersion(@RequestBody ResDrawVersionUpdateForm form) {
        int cancellation = resProductDrawService.updateDrawVersion(form);
        if (cancellation > 0) {
            return JsonResult.success("操作成功");
        }else{
            return JsonResult.fail("操作失败");
        }
    }


    /**
     * 设为默认
     * @param id
     * @return
     */
    @ApiOperation(value = "图纸", notes = "图纸-设为默认")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PutMapping("/setDefault/{id}")
    public JsonResult setDefault(@PathVariable("id") String id) {
        int cancellation = resProductDrawService.setDefault(id);
        if (cancellation > 0) {
            return JsonResult.success("操作成功");
        }else{
            return JsonResult.fail("操作失败");
        }
    }


    @Resource
    ProductDetailService productDetailService;

    /**
     * 下载产品图纸导入excel模板
     */
    @ApiOperation(value = "下载产品图纸导入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"附件地址(*)", "sku物料(*)","图纸类型(*)", "产品图纸名称(*)", "产品图纸Code(*)","版本名称(*)","备注"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();
        List<ProductDetail> productDetailList = productDetailService.list();
        if(CollectionUtil.isNotEmpty(productDetailList)){
            for (ProductDetail productBrand : productDetailList) {
                tempStr.append(productBrand.getSkuCode()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("1");
        }

        String[] picList = {"成品图纸", "工序图纸", "模具图纸"};
        for (String pic : picList) {
            tempStr.append(pic).append(",");
        }
        tempStr.delete(tempStr.length()-1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0,tempStr.length());
        indexArr.add("2");
        DownExcelUtil.createExcelTemplate(response, request, "产品图纸导入模板", Arrays.asList(headerArr), downData, indexArr);
    }



    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<DrawExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<DrawExcelIn> list = reader.read(is, DrawExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            resProductDrawService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

}
